import { AuthResultModal, DefaultConfigModal, RouteModal } from '../modal';
import { localNameProvider } from './loacl';
import { ACauth, itemAuthProvider } from './auth';
import { checkSameAuth } from './check';
const defaultData = (): AuthResultModal => {
  return {
    routes: [],
    components: [],
    apis: [],
  };
}; //默认数据
const routesItemControl = (
  config: DefaultConfigModal,
  route?: RouteModal,
  fatherNode?: RouteModal,
): AuthResultModal => {
  if (!route) {
    return defaultData();
  }

  const { childAuths, routes: childRoutes, auth, ...oRoute } = route;
  const result: AuthResultModal = defaultData();
  const localObj = localNameProvider(config, route, fatherNode); //国际化
  const pageAuth = itemAuthProvider(config, auth, fatherNode); //当前auth
  checkSameAuth(pageAuth); //检查是否重复key;
  const { components, apis } = ACauth(config, childAuths, fatherNode);
  result.apis.push(...apis);
  result.components.push(...components);

  const nRoute: RouteModal = {
    ...oRoute,
    ...localObj,
    auth: pageAuth || false,
    components,
    apis,
  };

  const child = routesProvider(config, childRoutes, nRoute);
  result.apis.push(...child.apis);
  result.components.push(...child.components);
  nRoute.routes = child.routes;
  result.routes.push(nRoute);

  return result;
}; //单个路由分离
export function routesProvider(
  config: DefaultConfigModal,
  routes?: RouteModal[],
  fatherNode?: RouteModal,
): AuthResultModal {
  const data = defaultData();

  if (!routes) {
    return data;
  }

  routes.map(item => {
    const { routes: itemRoutes, components, apis } = routesItemControl(
      config,
      item,
      fatherNode,
    );

    data.routes.push(...itemRoutes);
    data.apis.push(...apis);
    data.components.push(...components);
  });
  return data;
} //路由构建
